package everyday;

public class T2106 {
    int startPos;
    public int maxTotalFruits(int[][] fruits, int startPos, int k) {
        this.startPos = startPos;
        int leftIndex = 0, rightIndex = 0, n = fruits.length, sum = 0, ans = 0;
        while (rightIndex < n) {
            sum += fruits[rightIndex][1];
            while (leftIndex <= rightIndex && step(fruits[leftIndex][0],fruits[rightIndex][0])>k){
                sum-=fruits[leftIndex][1];
                leftIndex++;
            }
            ans=Math.max(ans,sum);
            rightIndex++;
        }
        return ans;
    }

    public int step(int left, int right) {
        return right - left + Math.min(Math.abs(right - startPos), Math.abs(startPos - left));
    }
}
